﻿using Set_File_Rw;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Input;
using TestFireBroadcastingHostPhone.DataBase;

namespace TestFireBroadcastingHostPhone.ViewModel
{
    public class UserLoadingMV : ViewModelBase
    {
        /// <summary>
        /// 管理员登陆的标志
        /// </summary>
        public bool administrator_loading = false;
        public static UserLoadingMV userLoadingMV { get; private set; }
        public UserLoadingMV()
        {
            userLoadingMV = this;
        }

        public ICommand UserLoading_LoadedCommand => new RelayCommand(OnUserLoading_LoadedCommand);
        /// <summary>
        /// 窗体载入
        /// </summary>
        /// <param name="obj"></param>
        public void OnUserLoading_LoadedCommand(object obj)
        {
            string err_info = string.Empty;
            string default_file_path = Directory.GetCurrentDirectory() + "\\RecordData\\RelatedRecord.ini";
            Text_UserName = Set_Data_Rw.Read(SystemConfigMV.configpath, default_file_path, "用户名", out err_info);
            Password_User = Set_Data_Rw.Read(SystemConfigMV.configpath, default_file_path, "用户名密码", out err_info);
            Text_SQL_Name = Set_Data_Rw.Read(SystemConfigMV.configpath, default_file_path, "服务器名称", out err_info);
            Password_SQL = Set_Data_Rw.Read(SystemConfigMV.configpath, default_file_path, "数据库密码", out err_info);
        }

        public string _SQL_Name = string.Empty;
        /// <summary>
        /// 数据库名
        /// </summary>
        public string Text_SQL_Name
        {
            get => this._SQL_Name;
            set
            {
                this._SQL_Name = value;
                OnPropertyChanged();
            }
        }

        public string? _SQL_Password;
        /// <summary>
        /// 数据库密码
        /// </summary>
        public string Password_SQL
        {
            get => this._SQL_Password;
            set
            {
                this._SQL_Password = value;
                OnPropertyChanged();
            }
        }

        public string _UserName = string.Empty;
        /// <summary>
        /// 用户名
        /// </summary>
        public string Text_UserName
        {
            get { return _UserName; }
            set
            {
                if (_UserName != value)
                {
                    _UserName = value;
                    OnPropertyChanged();
                }
            }
        }

        public string? _UserPassword;
        /// <summary>
        /// 用户的密码
        /// </summary>
        public string Password_User
        {
            get => this._UserPassword;
            set
            {
                this._UserPassword = value;
                OnPropertyChanged();
            }
        }

        public bool _RememberPassword;
        /// <summary>
        /// 记住密码选择
        /// </summary>
        public bool IsChecked_RememberPassword
        {
            get { return _RememberPassword; }
            set
            {
                if (_RememberPassword != value)
                {
                    _RememberPassword = value;
                    OnPropertyChanged(nameof(_RememberPassword));
                }
            }
        }

        public bool _AdminLogin;
        /// <summary>
        /// 管理员登录选择
        /// </summary>
        public bool IsChecked_AdminLogin
        {
            get { return _AdminLogin; }
            set
            {
                if (_AdminLogin != value)
                {
                    _AdminLogin = value;
                    OnPropertyChanged(nameof(_AdminLogin));
                }
            }
        }

        /// <summary>
        /// 绑定用户登录事件
        /// </summary>
        public ICommand Btn_UserLoadingCommand => new RelayCommand(OnBtn_UserLoadingCommand);
        /// <summary>
        /// 用户登录事件
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_UserLoadingCommand(object obj)
        {
            bool load_result = false;
            string err_info = string.Empty;
            load_result = UserLoad(out err_info);
            if (load_result && string.IsNullOrEmpty(err_info))
            {
                var mainWindow = new MainWindow();
                mainWindow.Show();
                CloseWindow();
            }
            else
            {
                MessageBox.Show(messageBoxText:$"登录失败: {err_info}", caption:"登录失败", MessageBoxButton.OK, icon:MessageBoxImage.Warning);
            }
        }
        /// <summary>
        /// 绑定退出事件
        /// </summary>
        public ICommand Btn_QuitApp_Command => new RelayCommand(OnBtn_QuitApp_Command);

        /// <summary>
        /// 退出事件
        /// </summary>
        /// <param name="obj"></param>
        public void OnBtn_QuitApp_Command(object obj)
        {
            CloseWindow();
        }
        /// <summary>
        /// 关闭当前登录窗口
        /// </summary>
        private void CloseWindow()
        {
            foreach (Window window in Application.Current.Windows)
            {
                if (window.GetType() == typeof(UserLoading))//使用窗体类进行匹配查找
                {
                    window.Close();
                }
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public bool UserLoad(out string err_info)
        {
            bool result = false;
            err_info = string.Empty;
            string user_info = string.Empty;
            string default_file_path = Directory.GetCurrentDirectory() + "\\RecordData\\RelatedRecord.ini";
            if (SQL_Login(out err_info) && string.IsNullOrEmpty(err_info))
            {
                if (!string.IsNullOrEmpty(Text_UserName) && !string.IsNullOrEmpty(Password_User))
                {
                    //是否为数据库中的管理员登录
                    if (IsChecked_AdminLogin == true)
                    {
                        user_info = SQL_ReadUserPassword(Text_UserName, out err_info);
                        if (Password_User == user_info)
                        {
                            result = true;
                            administrator_loading = true;
                        }
                        else
                        {
                            err_info = "管理员登录账号或密码错误,请重新输入!";
                            result = false;
                        }
                    }
                    else
                    {
                        result = true;
                    }
                    if (IsChecked_RememberPassword == true)
                    {
                        Set_Data_Rw.Write(SystemConfigMV.configpath, default_file_path, "用户名", Text_UserName, out err_info);
                        Set_Data_Rw.Write(SystemConfigMV.configpath, default_file_path, "用户名密码", Password_User, out err_info);
                    }
                }
                else
                {
                    result = false;
                }
            }
            else
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 数据库登录
        /// </summary>
        /// <returns></returns>
        private bool SQL_Login(out string err_info)
        {
            err_info = string.Empty;
            bool result = false;
            string default_file_path = Directory.GetCurrentDirectory() + "\\RecordData\\RelatedRecord.ini";
            if (!string.IsNullOrEmpty(Text_SQL_Name) && !string.IsNullOrEmpty(Password_SQL))
            {
                string connectionString = "DATA SOURCE=" + Text_SQL_Name + ";INITIAL CATALOG=" + "灯具测试" + ";USER ID=" + "test1" + ";PWD=" + Password_SQL;
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    try
                    {
                        if (connection.State != ConnectionState.Open) connection.Open();
                        Set_Data_Rw.Write(SystemConfigMV.configpath, default_file_path, "服务器名称", Text_SQL_Name, out err_info);
                        Set_Data_Rw.Write(SystemConfigMV.configpath, default_file_path, "数据库密码", Password_SQL, out err_info);
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        err_info = ex.ToString();
                        result = false;
                    }
                }
            }
            else
            {
                MessageBox.Show("请输入数据库账号与数据库密码!");
            }
            return result;
        }

        /// <summary>
        /// 读取数据库中的某个数据:根据ID读取序列号
        /// </summary>
        /// <param name="ID">ID</param>
        /// <param name="error_inf"></param>
        /// <returns></returns>
        public string SQL_ReadUserPassword(string User, out string error_inf)
        {
            error_inf = string.Empty;
            string password = string.Empty;
            string sql_connect_command_text = "DATA SOURCE=" + SQL_DataBase.SQL_Server_Name + ";INITIAL CATALOG=" + SQL_DataBase.SQL_Data_Base_Name + ";USER ID=" + SQL_DataBase.SQL_User_Name + ";PASSWORD=" + SQL_DataBase.SQL_User_Password;
            string sql_command_text = $"SELECT 用户密码 FROM {SQL_DataBase.SQL_Data_Base_Name}.dbo.广播主机功放测试用户管理数据表 WHERE 用户 = @用户";
            try
            {
                using (SqlConnection sql_connection = new SqlConnection(sql_connect_command_text))
                {
                    if (sql_connection.State != ConnectionState.Open)
                    {
                        sql_connection.Open();
                    }
                    using (SqlCommand sql_command = new SqlCommand(sql_command_text, sql_connection))
                    {
                        sql_command.Parameters.AddWithValue("@用户", User);
                        using (SqlDataReader reader = sql_command.ExecuteReader())
                        {
                            if (reader.HasRows && reader.Read())
                            {
                                password = reader["用户密码"].ToString();
                            }
                            else
                            {
                                error_inf = "未找到用户或密码为空";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error_inf = ex.Message;
            }
            return password;
        }
    }
}
